package com.example.springboot_admin.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot_admin.pojo.Users;
import com.example.springboot_admin.service.IUsersService;
import com.example.springboot_admin.util.JwtUtils;
import com.example.springboot_admin.util.MD5Util;
import com.example.springboot_admin.util.RedisUtils;
import com.example.springboot_admin.vo.ResponseMsg;
import io.jsonwebtoken.Claims;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author svblack
 * @since 2024-09-12
 */
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    IUsersService usersService;
    @Autowired
    RedisUtils redisUtils;

    @Value("${uploadPath}")
    String uploadPath;



    @PostMapping("/changePassword")
    public ResponseMsg changePassword(HttpServletRequest request,
                                      @RequestBody ChangePasswordRequest changePasswordRequest) {


        String token  = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        String subject = claims.getSubject();
        UserInfo obj = JSON.parseObject(subject, UserInfo.class);

        System.out.println("obj:" + obj);
        Integer userid = obj.getUser_id();

        if (userid == null) {
            return ResponseMsg.fail("请重新登录");
        }

        String oldPassword = changePasswordRequest.getOldPassword();
        String newPassword = changePasswordRequest.getNewPassword();

        try {
            // 查询用户
            QueryWrapper<Users> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userid);
            Users user = usersService.getOne(wrapper);

            if (user == null) {
                return ResponseMsg.fail("用户不存在");
            }

            // 验证旧密码
            if (!MD5Util.checkPassword(oldPassword, user.getPassword())) {
                return ResponseMsg.fail("旧密码不正确");
            }

            // 更新新密码（先进行 MD5 加密）
            user.setPassword(MD5Util.md5(newPassword));
            boolean updated = usersService.updateById(user);

            if (updated) {
                // 清除session中的用户信息，要求用户重新登录
//                request.getSession().invalidate();
                return ResponseMsg.success("密码修改成功，请重新登录");
            } else {
                return ResponseMsg.fail("密码修改失败");
            }
        } catch (Exception e) {
            return ResponseMsg.fail("发生错误：" + e.getMessage());
        }
    }

    @RequestMapping("addUsers")
    Integer doAdd(@RequestBody Users users){
        users.setAvatar("/uploads/"+users.getAvatar());
        return usersService.save(users)?0:1;
    }



    @RequestMapping("del")
    Integer del(int user_id){
        return usersService.removeById(user_id)?0:1;
    }

    @RequestMapping("delMult")
    Integer delMult(@RequestBody List<Integer> ids){
        System.out.println("ids:"+ids);
        usersService.removeByIds(ids);
        return 0;
    }

    @RequestMapping("list")
    IPage<Users> page(@RequestParam(defaultValue = "1") int page,
                      @RequestParam(defaultValue = "10") int limit){
        IPage<Users> page1 = new Page<>(page,limit); //分页条件
        return usersService.page(page1);
    }


    @RequestMapping("query")
    List<Users> query(String username) {
        if (username != null && !username.trim().isEmpty()) {
            return usersService.queryByUsername(username);
        } else {
            return usersService.list(); // 如果没有提供 username，则返回所有用户
        }
    }


    @RequestMapping("login")
    ResponseMsg login(@RequestBody Users user){
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        wrapper.eq("password", user.getPassword());
        Users result = usersService.getOne(wrapper);
        if(result==null){
            return ResponseMsg.loginFail();
        }
        //jwt tokem 唯一标识
        String uuid = UUID.randomUUID().toString();
        String subject="{'user_id':"+result.getUser_id()+",'username':'"+result.getUsername()+"'}";
        String jwtToken= JwtUtils.createJWT(uuid, subject, 1000*60*30);

        redisUtils.set(jwtToken,result,1800);
        // redisUtils.hset("jwt",jwtToken,result);//hash类型

        return ResponseMsg.loginSuccess(jwtToken);
    }


    @RequestMapping("profile")
    Profile profile(){
        Profile user = new Profile();
        user.setNickName("神经病");
        user.setResultCode(200);
        return user;
    }


    @RequestMapping("uploadImgs")
    ResponseMsg uploadImgs(MultipartFile file){

        String fileName = "";
        //得到服务器运行绝对路径
        File aFile = null;
        try {
            aFile = ResourceUtils.getFile("classpath:");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
//        String path = aFile.getAbsolutePath() + "/upload/";
        String path = uploadPath ;
        System.out.println("上传绝对路径:" + path);
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir(); //upload文件夹不存在就创建
        }
        if (null != file && !file.isEmpty()){
            //file.getOriginalFilename(); //得到上传文件的原始名字
            fileName = formateDate()  + file.getOriginalFilename();
            File savedFile = new File(path + fileName); //path+fileName文件的完整路径
            System.out.println(path + fileName);
            try {
                file.transferTo(savedFile); //保存文件对象到服务器本地磁盘
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResponseMsg.success(fileName);
    }

    String formateDate(){
        LocalDateTime now = LocalDateTime.now(); //得到当前日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        return formatter.format(now);
    }

}
@Data
class Profile{
    int adminUserId;
    String loginUserName;
    String nickName;
    int locked;
    int resultCode;
    String message;
}

@Data
class UserInfo{
    int user_id;
    String username;
}